import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { clearResultsAction, getResultsAction } from '@/store/action/search';
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';
import { InfiniteScroll } from 'antd-mobile';

export default function SearchResult() {
  const { search } = useLocation();
  const urlParams = new URLSearchParams(search);
  const keyword = urlParams.get('q') as string;

  const dispatch = useDispatch();

  useEffect(() => {
    return () => {
      dispatch(clearResultsAction());
    };
  }, [dispatch]);

  const pageRef = useRef(0);

  //  停掉加载更多

  const handleLoadMore = async () => {
    pageRef.current = pageRef.current + 1;
    await dispatch(getResultsAction(keyword, pageRef.current));
  };

  const { results } = useAppSelector((state) => state.search);

  // 3. 定义计算属性 计算hasMore是否为true
  // page * 10 代表理论上请求回来的总数，如果实际数量小于理论数量，代表数据已经被查光了
  // 换言之 page * 10 > resuls.lenght  代表没有更多数据了
  // 换言之 page * 10 <= results.length 代表还有更多的数据
  const hasMore = pageRef.current * 10 <= results.length;
  console.log('per_page, page, results.length  ----->  ', 10, pageRef.current, results.length);
  console.log(' hasMore  ----->  ', hasMore);
  return (
    <div className={styles.root}>
      <NavBar fixed>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} data={item} />
        ))}
      </div>

      <InfiniteScroll loadMore={handleLoadMore} hasMore={hasMore} />
    </div>
  );
}
